package com.netease.rtcdemo;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.SwitchPreference;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;


public class Settings extends PreferenceFragment implements Preference.OnPreferenceChangeListener,
        SharedPreferences.OnSharedPreferenceChangeListener{
    private final static int REQUEST_QRCODE_SCANNER_APPKEY_CODE = 10004;
    private NeutralEditTextPreference privateSettingEditTextPref;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        PreferenceManager.setDefaultValues(getActivity().getBaseContext(), R.xml.setting_pref, false);
        addPreferencesFromResource(R.xml.setting_pref);
        privateSettingEditTextPref = (NeutralEditTextPreference) findPreference(getString(R.string.private_setting));
        bindPreferenceSummaryToValue(privateSettingEditTextPref);
        privateSettingEditTextPref.setOnNeutralButtonClickListener((dialog, which) -> {
            startQrCodeScannerIntent(REQUEST_QRCODE_SCANNER_APPKEY_CODE);
        });
        // 获取 SwitchPreference 实例
        SwitchPreference switchPreference = (SwitchPreference)findPreference("private_setting_enable");
        if (switchPreference != null) {
            // 设置偏好设置改变监听器
            switchPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                    // 当 SwitchPreference 的状态发生改变时，会调用此方法
                    Toast.makeText(getActivity(), "需要杀死进程重启才能生效", Toast.LENGTH_SHORT).show();
                    return true;
                }
            });
        }
    }

    private Preference bindPreferenceSummaryToValue(Preference preference) {
        return bindPreferenceSummaryToValue(preference, null);
    }
    private void startQrCodeScannerIntent(int requestCode) {
        if (checkPermission(Manifest.permission.CAMERA)) {
            IntentIntegrator intentIntegrator = IntentIntegrator.forFragment(Settings.this);
            intentIntegrator.setRequestCode(requestCode);
            intentIntegrator.initiateScan();
        } else {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, 1);
        }
    }
    private boolean checkPermission(String permission) {
        return PackageManager.PERMISSION_GRANTED ==
                getActivity().checkPermission(permission,
                        android.os.Process.myPid(),
                        android.os.Process.myUid());
    }

    private Preference bindPreferenceSummaryToValue(Preference preference, Preference.OnPreferenceChangeListener listener) {
        Preference.OnPreferenceChangeListener delegate = listener == null ? this : (preference1, newValue) -> {
            onPreferenceChange(preference1, newValue);
            listener.onPreferenceChange(preference1, newValue);
            return true;
        };
        preference.setOnPreferenceChangeListener(delegate);
        bindPreferenceDefValue(preference);
        return preference;
    }

    private void bindPreferenceDefValue(Preference preference) {
        preference.getOnPreferenceChangeListener().onPreferenceChange(preference,
                PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext())
                        .getString(preference.getKey(), ""));
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK || data == null) {
            return;
        }
        int resId = 0;
        switch (requestCode) {
            case REQUEST_QRCODE_SCANNER_APPKEY_CODE:
                resId = R.string.private_setting;
                updateQrCodeResultForEtPref(resId, resultCode, data);
                break;
        }
    }
    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        String stringValue = newValue.toString();

        if (preference instanceof ListPreference) {
            ListPreference listPreference = (ListPreference) preference;
            int prefIndex = listPreference.findIndexOfValue(stringValue);
            if (prefIndex >= 0) {
                preference.setSummary(listPreference.getEntries()[prefIndex]);
            }
            Log.d("SettingsFragment", "onPreferenceChange: " + preference.getSummary() + ", " + newValue);
        } else if (preference instanceof SwitchPreference) {
            //ignore
        } else {
            preference.setSummary(stringValue);
        }
        return true;
    }

    private void updateQrCodeResultForEtPref(int resId, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(resultCode, data);
        if (result != null) {
            String content = result.getContents();
            NeutralEditTextPreference pref = (NeutralEditTextPreference) findPreference(getString(resId));
            pref.setSummary(content);
            pref.setText(content);
            PreferenceManager.getDefaultSharedPreferences(getActivity()).edit().putString(getString(resId), content).apply();
        }
    }
}